package com.industriallogic.blackjack;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class BlackjackRunner {

	private Player player = new Player();
	private Dealer dealer = new Dealer();
	
	private Deck deck = new Deck();

	public enum PlayerState {
		HIT, STAY, DOUBLE, SPLIT
	}

	public void play() {

		try {

			deal();

			dealer.printCardsInHand();

			int playerHand = 0;
			int dealerHand = 0;

			boolean busted = false;

			PlayerState state = PlayerState.HIT;

			while (state.equals(PlayerState.HIT) && !busted) {

				state = promptHitOrStay();

				if (state.equals(PlayerState.HIT)) {
					playerHand = player.hit(deck);
					if (playerHand > 21) {
						System.out.println("PLAYER BUSTED");
						busted = true;
					}
				}

			}

			// player stay
			if (busted) {
				System.out.println("DEALER WINS");
				return;
			}

			boolean dealerBust = false;
			while (!dealerBust && dealerHand < 17) {
				dealer.hit(deck);
				dealer.printCardsInHand();
				dealerHand = dealer.calculateHand();
			}

			if (dealerBust) {
				System.out.println("PLAYER WINS");
				return;
			}
			
			
			if(playerHand == dealerHand){
				System.out.println("DRAW");
				return;
			}
			
			if(playerHand > dealerHand){
				System.out.println("PLAYER WINS");
				return;
			}
			
			System.out.println("DEALER WINS");
			return;
			

		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private void deal() {
		player.hit(deck);
		dealer.hit(deck);
		player.hit(deck);
	}

	private PlayerState promptHitOrStay() throws IOException {
		player.printCardsInHand();
		
		System.out.println("1 - Hit, 2 - Stay");

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String s = br.readLine();
		String value = s.split("//s")[0];

		
		if ("1".equalsIgnoreCase(value)) {
			return PlayerState.HIT;
		}
		return PlayerState.STAY;

	}

	public Player getPlayer() {
		return player;
	}

	public void setPlayer(Player player) {
		this.player = player;
	}

	public Dealer getDealer() {
		return dealer;
	}

	public void setDealer(Dealer dealer) {
		this.dealer = dealer;
	}

}
